{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "class Antirectifier(layers.Layer):\n",
    "    def __init__(self,initializer='he_normal',**kwargs):\n",
    "        super(Antirectifier,self).__init__(**kwargs)\n",
    "        self.initializer = keras.initializers.get(initializer)\n",
    "    \n",
    "    def build(self,input_shape):\n",
    "        output_dim = input_shape[-1]\n",
    "        self.kernel = self.add_weight(\n",
    "            shape=(output_dim * 2,output_dim),\n",
    "            initializer=self.initializer,\n",
    "            name='kernel',\n",
    "            trainable=True\n",
    "        )\n",
    "    \n",
    "    def call(self,inputs):\n",
    "        inputs -= tf.reduce_mean(inputs,axis=-1,keepdims=True)\n",
    "        pos = tf.nn.relu(inputs)\n",
    "        neg = tf.nn.relu(-inputs)\n",
    "        concatenated = tf.concat([pos,neg],axis=-1)\n",
    "        mixed = tf.matmul(concatenated,self.kernel)\n",
    "        return mixed\n",
    "    \n",
    "    def get_config(self):\n",
    "        base_config = super(Antirectifier,self).get_config()\n",
    "        config = {'initializer':keras.initializers.serialize(self.initializer)}\n",
    "        return dict(list(base_config.items()) + list(config.items()))\n",
    "    \n",
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n",
     "is_executing": false
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [
    {
     "name": "stdout",
     "text": [
      "60000 train samples\n",
      "10000 test samples\n",
      "Epoch 1/20\n"
     ],
     "output_type": "stream"
    }
   ],
   "source": [
    "batch_size = 128\n",
    "num_classes = 10\n",
    "epochs = 20\n",
    "\n",
    "(x_train,y_train),(x_test,y_test) = keras.datasets.mnist.load_data()\n",
    "x_train = x_train.reshape(-1,784)\n",
    "x_test = x_test.reshape(-1,784)\n",
    "x_train = x_train.astype('float32')\n",
    "x_test = x_test.astype('float32')\n",
    "x_train /= 255\n",
    "x_test /= 255\n",
    "print(x_train.shape[0],'train samples')\n",
    "print(x_test.shape[0],'test samples')\n",
    "\n",
    "model = keras.Sequential([\n",
    "    keras.Input(shape=(784,)),\n",
    "    layers.Dense(256),\n",
    "    Antirectifier(),\n",
    "    layers.Dense(256),\n",
    "    Antirectifier(),\n",
    "    layers.Dropout(0.5),\n",
    "    layers.Dense(10)\n",
    "])\n",
    "\n",
    "model.compile(\n",
    "    loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
    "    optimizer = keras.optimizers.RMSprop(),\n",
    "    metrics = [keras.metrics.SparseCategoricalAccuracy()],\n",
    ")\n",
    "\n",
    "model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs,validation_split=0.15)\n",
    "model.evaluate(x_test,y_test)\n",
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n",
     "is_executing": true
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}